#!/usr/bin/env bash
database=$1
user=$2
password=$3
time=$(date "+%Y%m%d-%H%M")

path=$4


if [ -z "$database" ]; then
    echo "docker exec mongo mongo-export.sh 数据库 用户名 密码 备份目录"
    exit 1
fi

if [ -z "$path" ]; then
    path="/data/mongo/$database/$time"
fi

echo "target path: $path"
mkdir -p $path

mongo --quiet $database -u $user -p $password --eval "db.getCollectionNames()" \
  | xargs \
  | awk '{print substr($0,2,length()-2)}' \
  | { read c; ary=(${c//,/});  for i in ${ary[@]};  do echo $i;  done  ; } \
  | { readarray ary ; for i in ${ary[@]};  do echo "mongoexport -d $database -u $user -p $password --collection $i  -o $path/$i.json && echo '['$i' done！]'";  done  ; } \
  | bash

# 使用方式： docker exec mongo mongo-export.sh album dev 123 /data/db/0
# 3个参数：数据库，用户名，密码
